package cn.bocai.pc.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.bocai.pc.util.PCConstants;
import cn.bocai.pc.util.UploadResponse;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/** 
 * @className: BcUploadController
 * @description: 上传图片
 * @author: 99fu
 * @date: 2015年06月26日 下午6:20:31
 * @explain :多种方法处理上图片
 * @修改人：
 * @修改时间：
 * @修改内容：
 */
@Controller
@RequestMapping("/upload")
public class BcUploadController {

	//plupload 上传所需常量
	private static final long serialVersionUID = 3447685998419256747L;   
    private static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}";   
    private static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";   
    public static final String JSON = "application/json";   
    public static final int BUF_SIZE = 2 * 1024;   
    public static final String FileDir = "uploadfile/";   
    private int chunk;   
    private int chunks;   
    private String name;   
    private String user;   
    private String time; 
	/**
	 * 通过jquary的ajax请求，form提交方式上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/uploadPic.do")
	public void uploadPic(HttpServletRequest request, String fileName,
			PrintWriter out) {
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		CommonsMultipartFile cfile = (CommonsMultipartFile) mr
				.getFile(fileName);
		byte[] ftype = cfile.getBytes();
		String tfileName = "";
		tfileName = new SimpleDateFormat("yyyyMMddHHmmssSSS")
				.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			tfileName = tfileName + random.nextInt(10);
		}
		String suffix = "";
		String orgFileName = cfile.getOriginalFilename();
		suffix = orgFileName.substring(orgFileName.lastIndexOf("."));
		// 创建jersy客户端
		Client client = Client.create();
		// 指定图片服务器上的图片路径
		WebResource wr = client.resource(PCConstants.PIC_HOST + "/upload/"
				+ tfileName + suffix);
		// 直接上传图片到另一台主机
		wr.put(String.class, ftype);
		String realPath = PCConstants.PIC_HOST + "/upload/" + tfileName
				+ suffix;
		String raltivePath = "/upload/" + tfileName + suffix;
		// {"realPath":"http;///"}
		String result = "{\"realPath\":\"" + realPath
				+ "\", \"raltivePath\":\"" + raltivePath + "\"}";
		out.write(result);

	}
	/**
	 * 通过FCK提交方式上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/uploadForFck.do")
	public void uploadForFck(HttpServletRequest request, String fileName,
			PrintWriter out) {
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> map = mr.getFileMap();
		Set<String> set = map.keySet();
		String key = set.iterator().next();
		CommonsMultipartFile cfile = (CommonsMultipartFile) map.get(key);
		byte[] ftype = cfile.getBytes();
		String tfileName = "";
		tfileName = new SimpleDateFormat("yyyyMMddHHmmssSSS")
				.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			tfileName = tfileName + random.nextInt(10);
		}
		String suffix = "";
		String orgFileName = cfile.getOriginalFilename();
		suffix = orgFileName.substring(orgFileName.lastIndexOf("."));
		// 创建jersy客户端
		Client client = Client.create();
		// 指定图片服务器上的图片路径
		WebResource wr = client.resource(PCConstants.PIC_HOST + "/upload/"
				+ tfileName + suffix);
		// 直接上传图片到另一台主机
		wr.put(String.class, ftype);
		String realPath = PCConstants.PIC_HOST + "/upload/" + tfileName
				+ suffix;
		UploadResponse ur = new UploadResponse(UploadResponse.EN_OK, realPath);
		out.print(ur);

	}
	
	/**
	 * 通过plupload前台插件,多文件上传
	 * @param request
	 * @param fileName
	 * @return out
	 * @author 99fu
	 * @throws IOException 
	 * @time 2015年6月26日13:04:11
	 */
	@RequestMapping("/fileUpload")
	public void fileUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		 String responseString = RESP_SUCCESS;   
	        boolean isMultipart = ServletFileUpload.isMultipartContent(req);   
	        if(isMultipart){   
	            ServletFileUpload upload = new ServletFileUpload();   
	            try {   
	                FileItemIterator iter = upload.getItemIterator(req);   
	                while (iter.hasNext()) {   
	                    FileItemStream item = iter.next();   
	                    InputStream input = item.openStream();   
	                    // Handle a form field.   
	                    if(item.isFormField()){   
	                        String fileName = item.getFieldName();   
	                        String value = Streams.asString(input);   
	                        if("name".equals(fileName)){   
	                            this.name = value;   
	                        }else if("chunks".equals(fileName)){   
	                            this.chunks = Integer.parseInt(value);   
	                        }else if("chunk".equals(fileName)){   
	                            this.chunk = Integer.parseInt(value);   
	                        }else if("user".equals(fileName)){   
	                            this.user = value;   
	                        }else if("time".equals(fileName)){   
	                            this.time = value;   
	                        }   
	                    }   
	                    // Handle a multi-part MIME encoded file.   
	                    else {   
	                        String fileDir = req.getSession().getServletContext().getRealPath("/")+FileDir;   
	                        File dstFile = new File(fileDir);   
	                        if (!dstFile.exists()){   
	                            dstFile.mkdirs();   
	                        }   
	                        File dst = new File(dstFile.getPath()+ "/" + this.name);   
	                        saveUploadFile(input, dst);   
	  
	                    }   
	  
	                }   
	  
	            }   
	            catch (Exception e) {   
	                responseString = RESP_ERROR;   
	                e.printStackTrace();   
	            }   
	        }   
	        // Not a multi-part MIME request.   
	        else {   
	            responseString = RESP_ERROR;   
	        }   
	        if(this.chunk == this.chunks - 1){   
	            System.out.println("用户："+this.user);   
	            System.out.println("文件名称："+this.name);   
	            System.out.println("上传时间："+this.time);  
	        }   
	  
	        resp.setContentType(JSON);   
	        byte[] responseBytes = responseString.getBytes();   
	        resp.setContentLength(responseBytes.length);   
	        ServletOutputStream output = resp.getOutputStream();   
	        output.write(responseBytes);   
	        output.flush();   
	}
	
	 private void saveUploadFile(InputStream input, File dst) throws IOException {   
	        OutputStream out = null;   
	        try {   
	            if (dst.exists()) {   
	                out = new BufferedOutputStream(new FileOutputStream(dst, true),   
	                        BUF_SIZE);   
	            } else {   
	                out = new BufferedOutputStream(new FileOutputStream(dst),   
	                        BUF_SIZE);   
	            }   
	            byte[] buffer = new byte[BUF_SIZE];   
	            int len = 0;   
	            while ((len = input.read(buffer)) > 0) {   
	                out.write(buffer, 0, len);   
	            }   
	        } catch (Exception e) {   
	            e.printStackTrace();   
	        } finally {   
	            if (null != input) {   
	                try {   
	                    input.close();   
	                } catch (IOException e) {   
	                    e.printStackTrace();   
	                }   
	            }   
	  
	            if (null != out) {   
	                try {   
	                    out.close();   
	                } catch (IOException e) {   
	                    e.printStackTrace();   
	                }   
	            }   
	  
	        }   
	  
	    }   
}
